package upload

import (
	"errors"
	"fmt"
	"go.uber.org/zap"
	"io"
	"math/rand"
	"mime/multipart"
	"os"
	"path"
	"time"
	"wave-admin/global"
	"wave-admin/utils"
)

type Local struct{}

func (*Local) UploadFile(file *multipart.FileHeader) ([]string, string, error) {
	// 读取文件后缀
	ext := path.Ext(file.Filename)
	// 读取文件名并加密
	name := utils.Md5Encode(file.Filename + fmt.Sprintf("%d%04d",time.Now().Unix(), rand.Int31()))
	// 拼接新文件名
	filename := name + ext
	// 尝试创建此路径
	isPath, mkdirErr := utils.IsFileExist(global.GnConfig.Local.Path)
	if !isPath {
		os.MkdirAll(global.GnConfig.Local.Path,os.ModePerm)
	}
	if mkdirErr != nil {
		global.GnLog.Error("function os.MkdirAll() Filed", zap.Any("err", mkdirErr.Error()))
		return nil, "", errors.New("function os.MkdirAll() Filed, err:" + mkdirErr.Error())
	}
	// 拼接路径和文件名
	filePath := global.GnConfig.Local.Path + "/" + filename

	f, openError := file.Open() // 读取文件
	if openError != nil {
		global.GnLog.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
		return nil, "", errors.New("function file.Open() Filed, err:" + openError.Error())
	}
	defer f.Close() // 创建文件 defer 关闭

	out, createErr := os.Create(filePath)
	if createErr != nil {
		global.GnLog.Error("function os.Create() Filed", zap.Any("err", createErr.Error()))

		return nil, "", errors.New("function os.Create() Filed, err:" + createErr.Error())
	}
	defer out.Close() // 创建文件 defer 关闭

	_, copyErr := io.Copy(out, f) // 传输（拷贝）文件
	if copyErr != nil {
		global.GnLog.Error("function io.Copy() Filed", zap.Any("err", copyErr.Error()))
		return nil, "", errors.New("function io.Copy() Filed, err:" + copyErr.Error())
	}
	urls := []string{utils.TransformImageUrl("/" + filePath)}

	return urls, filename, nil
}